import PropTypes from 'prop-types'
import get from 'lodash/get'
import React, { useEffect, useRef, useState, useContext } from 'react'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock'
import { toast } from 'react-toastify'

import useWindowsUtils from '../../utils/WindowsUtils'
import FieldInput from '../../common/builder/FieldInput'

import { InitializrContext } from '../../reducer/Initializr'

function Popover({ gitlabUrl, open, onClose }) {
  const [datas, setValues] = useState({
    gitlab: {
      url: '',
      token: '',
      teamName: '',
      projectName: '',
      projectDescription: '',
    },
  })
  const [button, setButton] = useState('导入项目至GitLab')
  const wrapper = useRef(null)
  const input = useRef(null)
  const windowsUtils = useWindowsUtils()
  const [error, setError] = useState('')

  const {
    values,
    dispatch: dispatchInitializr,
    errors,
  } = useContext(InitializrContext)

  useEffect(() => {
    // 如果 values.meta.name 存在，则设置为 projectName 的默认值
    const name = values.meta ? values.meta.name : ''
    const description = values.meta ? values.meta.description : ''
    setValues(prev => ({
      ...prev,
      gitlab: {
        ...prev.gitlab,
        projectName: name,
        projectDescription: description,
      },
    }))
  }, [values.meta])
  useEffect(() => {
    const clickOutside = event => {
      const children = get(wrapper, 'current')
      if (children && !children.contains(event.target)) {
        onClose()
      }
    }
    document.addEventListener('mousedown', clickOutside)
    if (get(input, 'current')) {
      get(input, 'current').focus()
    }
    return () => {
      document.removeEventListener('mousedown', clickOutside)
    }
  }, [onClose, input])

  const onEnter = () => {
    setButton('导入项目至GitLab')
  }
  useEffect(() => {
    if (get(wrapper, 'current') && open) {
      disableBodyScroll(get(wrapper, 'current'))
    }
    return () => {
      clearAllBodyScrollLocks()
    }
  }, [wrapper, open])
  useEffect(() => {
    // 调用后台接口获取 gitlab.url 的默认值
    const fetchGitlabUrl = async () => {
      try {
        const response = await fetch(`${windowsUtils.origin}/gitlab/meta`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        })
        if (response.ok) {
          const data = await response.text()
          const res = JSON.parse(data)
          setValues(prev => ({
            ...prev,
            gitlab: {
              ...prev.gitlab,
              url: res.url,
              token: res.personalAccessToken,
              teamName: res.teamName,
            },
          }))
        } else {
          throw new Error('请检查后台的URL配置！')
        }
      } catch (error) {
        toast.error(`请检查网络或后台服务！`)
      }
    }
    fetchGitlabUrl()
  }, [windowsUtils.origin])
  const onImport = async () => {
    setError('')
    try {
      if (Object.keys(datas.gitlab).some(key => !datas.gitlab[key].trim())) {
        toast.error(`请输入Gitlab完整信息！`)
        return
      }
      Object.keys(datas.gitlab).forEach(key => {
        if (!values.hasOwnProperty(key)) {
          values[key] = datas.gitlab[key]
        }
      })
      const urlToGitlab = `${windowsUtils.origin}/gitlab/import`
      const response = await fetch(urlToGitlab, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      })
      const data = await response.text()
      if (response.ok) {
        toast.success(data)
        onClose()
      } else {
        toast.warning(data)
      }
    } catch (error) {
      toast.error(`请检查网络！`)
    }
  }

  const handleChange = (field, subField) => event => {
    const value = event.target.value
    setValues(prevValues => ({
      ...prevValues,
      [field]: {
        ...prevValues[field],
        [subField]: value,
      },
    }))
  }

  return (
    <TransitionGroup component={null}>
      {open && (
        <CSSTransition onEnter={onEnter} classNames='popup' timeout={300}>
          <div className='popup-share'>
            <div className='popop-share-container' ref={wrapper}>
              <div className='popup-header'>
                <h1>配置导入项目至GitLab</h1>
              </div>
              <div className='popup-content'>
                <div className='control'>
                  <FieldInput
                    id='input-gitlabUrl'
                    value={datas.gitlab.url}
                    text='Gitlab地址'
                    onChange={handleChange('gitlab', 'url')}
                  />
                </div>
                <div className='control'>
                  <FieldInput
                    id='input-token'
                    value={datas.gitlab.token}
                    text='Gitlab的Token'
                    onChange={handleChange('gitlab', 'token')}
                  />
                </div>
                <div className='control'>
                  <FieldInput
                    id='input-teamName'
                    value={datas.gitlab.teamName}
                    text='群组名称'
                    onChange={handleChange('gitlab', 'teamName')}
                  />
                </div>
                <div className='control'>
                  <FieldInput
                    id='input-projectName'
                    value={datas.gitlab.projectName}
                    text='项目名称'
                    onChange={handleChange('gitlab', 'projectName')}
                  />
                </div>
                <div className='control'>
                  <FieldInput
                    id='input-projectDescription'
                    value={datas.gitlab.projectDescription}
                    text='项目描述'
                    onChange={handleChange('gitlab', 'projectDescription')}
                  />
                </div>
              </div>
              <div className='popup-action'>
                <a
                  href='/#'
                  onClick={e => {
                    e.preventDefault()
                    onImport()
                  }}
                  className='button'
                >
                  <span className='button-content' tabIndex='-1'>
                    <span>{button}</span>
                  </span>
                </a>
              </div>
            </div>
          </div>
        </CSSTransition>
      )}
    </TransitionGroup>
  )
}

Popover.propTypes = {
  gitlabUrl: PropTypes.string.isRequired,
  open: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
}

export default Popover
